from django.shortcuts import render
from django.views import View
from apps.goods.models import SKU
from apps.contents.models import GoodsCategory
from apps.goods.utils import get_breadcrumb
from apps.contents.models import GoodsChannel
from django import http
from haystack.views import SearchView
from django.core.paginator import Paginator, EmptyPage
# Create your views here.



class MySearchView(SearchView):
    '''重写SearchView类'''
    def create_response(self):
        # 获取检索到的数据
        context = self.get_context()

        # 获取检索到的模型数据
        results = context['page'].object_list

        # 遍历results，取出检索到的SKU，再转字典列表
        data_list = []
        for result in results:
            data_list.append({
                'id': result.object.id,
                'name': result.object.name,
                'price': result.object.price,
                'default_image_url': result.object.default_image.url,
                'searchkey': context.get('query'),
                'page_size': context['page'].paginator.num_pages,  # 分页后的总页数
                'count': context['page'].paginator.count
            })

        # 将检索到数据转成JSON返回即可
        return http.JsonResponse(data_list, safe=False)


# class SortView(View):
#     def get(self, request):
#         # 准备商品分类数据的字典容器
#         categories = {}
#
#         # 查询所有的37个频道(一级分类)
#         # GoodsChannel.objects.all().order_by('group_id', 'sequence')
#         channels = GoodsChannel.objects.order_by('group_id', 'sequence')
#         # 遍历所有的频道，取出每一个频道
#         for channel in channels:
#             # 通过频道数据关联的组取出对应的组号
#             group_id = channel.group.id
#             # 将group_id作为categories字段的key
#             if group_id not in categories:
#                 categories[group_id] = {'channels': [], 'sub_cats': []}
#
#             # 获取当前频道关联的一级分类（一个频道对应一个一级分类）
#             cat1 = channel.category
#             # 添加每组中对应的频道数据
#             categories[group_id]['channels'].append({
#                 "id": channel.id,
#                 "name": cat1.name,
#                 "url": channel.url
#             })
#
#             # 添加每组中的二级和三级分类
#             for cat2 in cat1.subs.all():
#                 # 使用二级分类查询关联的三级分类
#                 sub_cats = []
#                 for cat3 in cat2.subs.all():
#                     sub_cats.append({
#                         "id": cat3.id,  # 三级分类ID
#                         "name": cat3.name  # 三级分类名字
#                     })
#
#                 categories[group_id]['sub_cats'].append({
#                     "id": cat2.id,  # 二级分类ID
#                     "name": cat2.name,  # 二级分类名字
#                     "sub_cats": sub_cats  # 二级关联的三级分类
#                 })
#
#         return http.JsonResponse({'code':0,
#                                   'errmsg':'ok',
#                                   'categories':categories})


class HotGoodsView(View):
    """商品热销排行"""

    def get(self, request, category_id):
        """提供商品热销排行 JSON 数据"""
        # 根据销量倒序
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code': 400,
                                      'errmsg': 'category_id不存在'})

        skus = SKU.objects.filter(category=category, is_launched=True).order_by('-sales')[:2]

        hot_skus = []
        for sku in skus:
            hot_skus.append({
                'id': sku.id,
                'default_image_url': sku.default_image.url,
                'name': sku.name,
                'price': sku.price
            })

        return http.JsonResponse({'code':0,
                                  'errmsg':'ok',
                                  'hot_skus':hot_skus})


class ListView(View):
    """商品列表页"""

    def get(self, request, category_id):
        """提供商品列表页"""
        # 获取参数:
        page_num = request.GET.get('page')      #当前用户想看的页码
        page_size = request.GET.get('page_size')    #改页中想看的记录个数
        ordering = request.GET.get('ordering')  #排序字段

        #检验参数
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return http.JsonResponse({'code':400,
                                      'errmsg':'category_id不存在'})

        #实现核心逻辑 :排序, 面包屑导航, 分页
            #查询指定分类下未被下架的商品
        skus = SKU.objects.filter(category=category, is_launched=True).order_by(ordering)

            #分页查询
        paginator = Paginator(skus, page_size)

            #获取指定页中的模型数据
        try:
            page_skus = paginator.page(page_num)
        except EmptyPage:
            return http.JsonResponse({'code':400, 'errmsg':'页码错误'})

            #获取分页后的总页数
        total_page = paginator.num_pages

            # 面包屑导航(封装了一个函数utils)
        breadcrumb = get_breadcrumb(category)

        list = []
        for i in page_skus:
            list.append({
                'id': i.id,
                'default_image_url': i.default_image.url,
                'name': i.name,
                'price': i.price
            })
        #响应结果
        return http.JsonResponse({'code':0,
                                'errmsg':'ok',
                                'breadcrumb': breadcrumb,   # 面包屑导航
                                'list':list,
                                'count':total_page
                                 })